package com.ym521.logdog.utils

import java.security.NoSuchAlgorithmException
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

/**
 * @author YM
 * @E-mail 2435970206@qq
 * @QQ 2435970206
 * AES 加密
 */
internal object AESecurityUtil {

    private const val AES_MODEL = "AES/ECB/PKCS5Padding"

    /**
     * AES加密字符串
     *
     * 需要被加密的字符串
     * @param content
     *
     * 加密需要的秘钥
     * @param keyBytes
     * @return 密文
     */
    fun encrypt(content: String, keyBytes: ByteArray): String {
        try {
            if (keyBytes.size != 16) {
                throw RuntimeException("LOGDOG AES Key 不符合 16 个byte！！！")
            }
            val key = SecretKeySpec(keyBytes, "AES") // 转换为AES专用密钥
            val cipher: Cipher = Cipher.getInstance(AES_MODEL) // 创建密码器
            val byteContent = content.toByteArray(Charsets.UTF_8)
            cipher.init(Cipher.ENCRYPT_MODE, key) // 初始化为加密模式的密码器
            val dataBytes = cipher.doFinal(byteContent)
            return Base64.getEncoder().encodeToString(dataBytes)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        throw RuntimeException("LOGDOG AES 加密失败")
    }


    /**
     * 解密AES加密过的字符串
     *
     *AES加密过过的内容
     * @param content
     * 加密需要的秘钥
     * @param keyBytes
     *
     * @return 明文
     */
    fun decrypt(content: String, keyBytes: ByteArray): String {
        try {
            if (keyBytes.size != 16) {
                throw RuntimeException("LOGDOG AES Key 不符合 16 个byte！！！")
            }
            val dataBytes = Base64.getDecoder().decode(content)
            val key = SecretKeySpec(keyBytes, "AES") // 转换为AES专用密钥
            val cipher: Cipher = Cipher.getInstance(AES_MODEL) // 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key) // 初始化为解密模式的密码器
            return String(cipher.doFinal(dataBytes), Charsets.UTF_8) // 明文
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        throw RuntimeException("LOGDOG AES 解密失败")
    }

}